/*
 * Copyright (c) 2017 22420103@QQ.COM 版权所有
 */
package com.lehe.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lehe.common.exceptions.LHAdminException;
import com.lehe.dao.GoldRebateDao;
import com.lehe.entry.GoldRebateDto;
import com.lehe.entry.dbbean.GoldDetailDto;
import com.lehe.entry.dbbean.RebateBalanceDto;
import com.lehe.entry.dbbean.RebateDto;

/**
 * 用户代理操作
 *
 * @author wq
 * @since 2018-03-12
 */
@Transactional
@Service
public class GoldRebateService extends AbstractService {
	
	@Value("${config.leve1Persent}")
    private Integer leve1Persent;
	
	@Value("${config.leve2Persent}")
    private Integer leve2Persent;
	
	@Value("${config.leve3Persent}")
    private Integer leve3Persent;
	
	@Autowired
    private GoldRebateDao goldRebateDao;
	
	public Map<String, Object> goldRebate(String dt) throws LHAdminException {
		List<RebateDto> queryRebateDtail = goldRebateDao.queryRebateDtail(dt);
		Map<String, Object> returnMap=new HashMap<String, Object>();
		//已经存在提成数据 指定日期的 提成已经计算完成了 则 直接从数据库取数
		if(queryRebateDtail!=null && queryRebateDtail.size()>0 && queryRebateDtail.get(0)!=null){
			RebateDto rebateDto = queryRebateDtail.get(0);
			List<GoldDetailDto> goldDtailList = goldRebateDao.queryGoldDtailByPid(rebateDto.getId());

			List<RebateBalanceDto> rebateBalanceList = goldRebateDao.queryRebateBalanceByPid(rebateDto.getId());
			returnMap.put("execute", 1);
			returnMap.put("rebateDto", rebateDto);
			returnMap.put("goldDtailList", goldDtailList);
			returnMap.put("rebateBalanceList", rebateBalanceList);
		}else{
			returnMap =  queryGoldRebate(dt);
		}
		
		return returnMap;
	}
	
	/**
	 * @Description:计算提成 返回 XH_Rebate_Balance 数据  和 XH_GoldDetail<br/>
	 * 	returnMap.put("rebateDto", rebateDto);<br/>
		returnMap.put("goldDtailList", goldDtailList);<br/>
		returnMap.put("rebateBalanceList", rebateBalanceList);<br/>
		returnMap.put("execute", 0);//0 未执行 1执行了 2无税收记录
	* @author:wq
	* @date:2018年3月13日
	* @parameter:
	 */
	public synchronized Map<String, Object> queryGoldRebate(String dt) throws LHAdminException {
		clean();
		List<GoldRebateDto> queryGoldRebate = goldRebateDao.queryGoldRebate(dt);
		List<GoldDetailDto> goldDtailList=new ArrayList<GoldDetailDto>();
		Map<String, Object> returnMap=new HashMap<String, Object>();
		//当天无税收记录
		if(queryGoldRebate==null || queryGoldRebate.size()<=0 || queryGoldRebate.get(0)==null){
			returnMap.put("execute", 2);
			return returnMap;
		}
		for (GoldRebateDto goldRebateDto : queryGoldRebate) {
			//代理和普通玩家的提成计算 区分开   1表示 是 代理的消耗
			if(goldRebateDto.getUtype()==1){
				List<GoldDetailDto> agentUserGoldRebate = agentUserGoldRebate(goldRebateDto);
				goldDtailList.addAll(agentUserGoldRebate);
			}else if(goldRebateDto.getUtype()==0){
				List<GoldDetailDto> commonUserGoldRebate = commonUserGoldRebate(goldRebateDto);
				goldDtailList.addAll(commonUserGoldRebate);
			}else if(goldRebateDto.getUtype()==-1){
				System.out.println(goldRebateDto.getUserId()+" 自由玩家不需要计算提成 ");
			}else{
				throw new LHAdminException("存在错误的用户类型！");
			}
			score+=goldRebateDto.getRevenue();
		}
		List<RebateBalanceDto> rebateBalanceList =new ArrayList<RebateBalanceDto>(balanceMap.values());
		RebateDto rebateDto = new RebateDto();
		rebateDto.setDateId(queryGoldRebate.get(0).getDateID());
		rebateDto.setCollectDate(queryGoldRebate.get(0).getCollectDate());
		rebateDto.setScore(score);
		rebateDto.setRebateAmt(rebateAmt);
		rebateDto.setTopRebateAmt(topRebateAmt);
		rebateDto.setUserCount(userCount);
		rebateDto.setTopUserCount(topUserCount);
		rebateDto.setDetailCount(Long.valueOf(goldDtailList.size()));
		
		returnMap.put("rebateDto", rebateDto);
		returnMap.put("goldDtailList", goldDtailList);
		returnMap.put("rebateBalanceList", rebateBalanceList);
		returnMap.put("execute", 0);//0 未执行 1执行了 2无税收记录
		clean();
		return returnMap;
	}
	private void clean(){
		balanceMap=new ConcurrentHashMap<String,RebateBalanceDto>();
		score=0l;// 本次税收的总额
		rebateAmt=0l;//本次代理提成的总额
		topRebateAmt=0l;//本次运营号提成的总额
		userCount=0l;//本次计算提成涉及到代理数量
		topUserCount=0l;
	}
	/**
	 * 存储用户余额和提成 的map 一个用户只会有一条记录
	 */
	private Map<String,RebateBalanceDto> balanceMap=new ConcurrentHashMap<String,RebateBalanceDto>();
	
	private Long score=0l;// 本次税收的总额
	private Long rebateAmt=0l;//本次代理提成的总额
	private Long topRebateAmt=0l;//本次运营号提成的总额
	private Long userCount=0l;//本次计算提成涉及到代理数量
	private Long topUserCount=0l;//本次计算提成涉及到运营号数量
	
	/**
	 * @Description:根据userId 和 utype 获得用户余额 和提成
	* @author:wq
	* @date:2018年3月13日
	* @parameter:
	 */
	private Long getBalance(Long userID,GoldRebateDto goldRebateDto,Long rebate,Long uType){
		RebateBalanceDto oldBalance = balanceMap.get(uType+""+userID);
		if(oldBalance==null ){
			oldBalance=new RebateBalanceDto();
			oldBalance.setUserId(userID);
			oldBalance.setUserType(uType);
			oldBalance.setRebateScore(rebate);
			if(uType==1l){
				userCount++;
			}else if(uType==2l){
				topUserCount++;
			}else{
				
			}
			balanceMap.put(uType+""+userID, oldBalance);
		}else{
			oldBalance.setRebateScore(oldBalance.getRebateScore()+rebate);
			balanceMap.put(uType+""+userID, oldBalance);
		}
		return oldBalance.getRebateScore();
	}
	/**
	 * @Description:代理玩家提成计算
	* @author:wq
	* @date:2018年3月13日
	* @parameter:
	 */
	private List<GoldDetailDto> agentUserGoldRebate(GoldRebateDto goldRebateDto){
		List<GoldDetailDto> goldDetail=new ArrayList<GoldDetailDto>();
		//先返给自己
		GoldDetailDto zjGoldDetail=new GoldDetailDto();
		zjGoldDetail.setUserType(goldRebateDto.getUtype());
		long rebate = (long)(goldRebateDto.getRevenue()*leve1Persent/100);
		zjGoldDetail.setAmt(rebate);
		rebateAmt+=rebate;
		Long balance = getBalance(goldRebateDto.getUserId(),goldRebateDto, rebate,1l)+goldRebateDto.getGoldCoinCount();
		zjGoldDetail.setBalance(balance);
		zjGoldDetail.setCrtDate(goldRebateDto.getCollectDate());
		zjGoldDetail.setCrtOpr(1l);
		zjGoldDetail.setDateID(goldRebateDto.getDateID());
		zjGoldDetail.setKindID(goldRebateDto.getKindID());
		zjGoldDetail.setSourceUserId(goldRebateDto.getUserId());
		zjGoldDetail.setUserId(goldRebateDto.getUserId());
		zjGoldDetail.setBusiType(2);
		zjGoldDetail.setScore(goldRebateDto.getRevenue());
		zjGoldDetail.setPersent(leve1Persent.longValue());
		goldDetail.add(zjGoldDetail);
		//再返给自己的上级代理
		if(goldRebateDto.getFatherId1()!=null && !"".equals(goldRebateDto.getFatherId1())){			
			GoldDetailDto sjGoldDetail=new GoldDetailDto();
			sjGoldDetail.setUserType(1l);
			long sjRebate = (long)(goldRebateDto.getRevenue()*leve2Persent/100);
			sjGoldDetail.setAmt(sjRebate);
			rebateAmt+=sjRebate;
			Long sjbalance = getBalance(goldRebateDto.getFatherId1(),goldRebateDto, sjRebate,1l)+goldRebateDto.getGoldCoinCount1();
			sjGoldDetail.setBalance(sjbalance);
			sjGoldDetail.setCrtDate(goldRebateDto.getCollectDate());
			sjGoldDetail.setCrtOpr(1l);
			sjGoldDetail.setDateID(goldRebateDto.getDateID());
			sjGoldDetail.setKindID(goldRebateDto.getKindID());
			sjGoldDetail.setSourceUserId(goldRebateDto.getUserId());
			sjGoldDetail.setUserId(goldRebateDto.getFatherId1());
			sjGoldDetail.setBusiType(2);
			sjGoldDetail.setScore(goldRebateDto.getRevenue());
			sjGoldDetail.setPersent(leve2Persent.longValue());
			goldDetail.add(sjGoldDetail);
		}
		//再返给上上级代理
		if(goldRebateDto.getFatherId2()!=null && !"".equals(goldRebateDto.getFatherId2())){	
			GoldDetailDto ssjGoldDetail=new GoldDetailDto();
			ssjGoldDetail.setUserType(1l);
			long ssjRebate = (long)(goldRebateDto.getRevenue()*leve3Persent/100);
			ssjGoldDetail.setAmt(ssjRebate);
			rebateAmt+=ssjRebate;
			Long ssjbalance = getBalance(goldRebateDto.getFatherId2(),goldRebateDto, ssjRebate,1l)+goldRebateDto.getGoldCoinCount2();
			ssjGoldDetail.setBalance(ssjbalance);
			ssjGoldDetail.setCrtDate(goldRebateDto.getCollectDate());
			ssjGoldDetail.setCrtOpr(1l);
			ssjGoldDetail.setDateID(goldRebateDto.getDateID());
			ssjGoldDetail.setKindID(goldRebateDto.getKindID());
			ssjGoldDetail.setSourceUserId(goldRebateDto.getUserId());
			ssjGoldDetail.setUserId(goldRebateDto.getFatherId2());
			ssjGoldDetail.setBusiType(2);
			ssjGoldDetail.setScore(goldRebateDto.getRevenue());
			ssjGoldDetail.setPersent(leve3Persent.longValue());
			goldDetail.add(ssjGoldDetail);
		}
		//再返给运营号
		GoldDetailDto yyhGoldDetail=new GoldDetailDto();
		yyhGoldDetail.setUserType(2l);
		long yyhRebate = (long)(goldRebateDto.getRevenue()*goldRebateDto.getPersent()/100);
		yyhGoldDetail.setAmt(yyhRebate);
		topRebateAmt+=yyhRebate;
		Long yyhbalance = getBalance(goldRebateDto.getTopId(),goldRebateDto, yyhRebate,2l)+goldRebateDto.getTopGoldCoinCount();
		yyhGoldDetail.setBalance(yyhbalance);
		yyhGoldDetail.setCrtDate(goldRebateDto.getCollectDate());
		yyhGoldDetail.setCrtOpr(1l);
		yyhGoldDetail.setDateID(goldRebateDto.getDateID());
		yyhGoldDetail.setKindID(goldRebateDto.getKindID());
		yyhGoldDetail.setSourceUserId(goldRebateDto.getUserId());
		yyhGoldDetail.setUserId(goldRebateDto.getTopId());
		yyhGoldDetail.setBusiType(2);
		yyhGoldDetail.setScore(goldRebateDto.getRevenue());
		yyhGoldDetail.setPersent(goldRebateDto.getPersent().longValue());
		goldDetail.add(yyhGoldDetail);
		
		return goldDetail;
	}
	/**
	 * @Description:普通玩家提成计算
	* @author:wq
	 * @throws LHAdminException 
	* @date:2018年3月13日
	* @parameter:
	 */
	private List<GoldDetailDto> commonUserGoldRebate(GoldRebateDto goldRebateDto) throws LHAdminException{
		List<GoldDetailDto> goldDetail=new ArrayList<GoldDetailDto>();
		
		//先返给自己的上级代理

		if(goldRebateDto.getFatherId1()!=null && !"".equals(goldRebateDto.getFatherId1())){	
			GoldDetailDto sjGoldDetail=new GoldDetailDto();
			sjGoldDetail.setUserType(1l);
			long sjRebate = (long)(goldRebateDto.getRevenue()*leve1Persent/100);
			sjGoldDetail.setAmt(sjRebate);
			rebateAmt+=sjRebate;
			Long sjbalance = getBalance(goldRebateDto.getFatherId1(),goldRebateDto, sjRebate,1l)+goldRebateDto.getGoldCoinCount1();
			sjGoldDetail.setBalance(sjbalance);
			sjGoldDetail.setCrtDate(goldRebateDto.getCollectDate());
			sjGoldDetail.setCrtOpr(1l);
			sjGoldDetail.setDateID(goldRebateDto.getDateID());
			sjGoldDetail.setKindID(goldRebateDto.getKindID());
			sjGoldDetail.setSourceUserId(goldRebateDto.getUserId());
			sjGoldDetail.setUserId(goldRebateDto.getFatherId1());
			sjGoldDetail.setBusiType(2);
			sjGoldDetail.setScore(goldRebateDto.getRevenue());
			sjGoldDetail.setPersent(leve1Persent.longValue());
			goldDetail.add(sjGoldDetail);
		}
		//再返给上上级代理
		if(goldRebateDto.getFatherId2()!=null && !"".equals(goldRebateDto.getFatherId2())){	
			GoldDetailDto ssjGoldDetail=new GoldDetailDto();
			ssjGoldDetail.setUserType(1l);
			long ssjRebate = (long)(goldRebateDto.getRevenue()*leve2Persent/100);
			ssjGoldDetail.setAmt(ssjRebate);
			rebateAmt+=ssjRebate;
			Long ssjbalance = getBalance(goldRebateDto.getFatherId2(),goldRebateDto, ssjRebate,1l)+goldRebateDto.getGoldCoinCount2();
			ssjGoldDetail.setBalance(ssjbalance);
			ssjGoldDetail.setCrtDate(goldRebateDto.getCollectDate());
			ssjGoldDetail.setCrtOpr(1l);
			ssjGoldDetail.setDateID(goldRebateDto.getDateID());
			ssjGoldDetail.setKindID(goldRebateDto.getKindID());
			ssjGoldDetail.setSourceUserId(goldRebateDto.getUserId());
			ssjGoldDetail.setUserId(goldRebateDto.getFatherId2());
			ssjGoldDetail.setBusiType(2);
			ssjGoldDetail.setScore(goldRebateDto.getRevenue());
			ssjGoldDetail.setPersent(leve2Persent.longValue());
			goldDetail.add(ssjGoldDetail);
		}
		//再返给上上上级代理
		if(goldRebateDto.getFatherId3()!=null && !"".equals(goldRebateDto.getFatherId3())){
			GoldDetailDto sssjGoldDetail=new GoldDetailDto();
			sssjGoldDetail.setUserType(1l);
			long sssjRebate = (long)(goldRebateDto.getRevenue()*leve3Persent/100);
			sssjGoldDetail.setAmt(sssjRebate);
			rebateAmt+=sssjRebate;
			Long sssjbalance = getBalance(goldRebateDto.getFatherId3(),goldRebateDto, sssjRebate,1l)+goldRebateDto.getGoldCoinCount3();
			sssjGoldDetail.setBalance(sssjbalance);
			sssjGoldDetail.setCrtDate(goldRebateDto.getCollectDate());
			sssjGoldDetail.setCrtOpr(1l);
			sssjGoldDetail.setDateID(goldRebateDto.getDateID());
			sssjGoldDetail.setKindID(goldRebateDto.getKindID());
			sssjGoldDetail.setSourceUserId(goldRebateDto.getUserId());
			sssjGoldDetail.setUserId(goldRebateDto.getFatherId3());
			sssjGoldDetail.setBusiType(2);
			sssjGoldDetail.setScore(goldRebateDto.getRevenue());
			sssjGoldDetail.setPersent(leve3Persent.longValue());
			goldDetail.add(sssjGoldDetail);
		}
		//再返给运营号
		GoldDetailDto yyhGoldDetail=new GoldDetailDto();
		yyhGoldDetail.setUserType(2l);
		long yyhRebate = (long)(goldRebateDto.getRevenue()*goldRebateDto.getPersent()/100);
		yyhGoldDetail.setAmt(yyhRebate);
		topRebateAmt+=yyhRebate;
		Long yyhbalance = getBalance(goldRebateDto.getTopId(),goldRebateDto, yyhRebate,2l)+goldRebateDto.getTopGoldCoinCount();
		yyhGoldDetail.setBalance(yyhbalance);
		yyhGoldDetail.setCrtDate(goldRebateDto.getCollectDate());
		yyhGoldDetail.setCrtOpr(1l);
		yyhGoldDetail.setDateID(goldRebateDto.getDateID());
		yyhGoldDetail.setKindID(goldRebateDto.getKindID());
		yyhGoldDetail.setSourceUserId(goldRebateDto.getUserId());
		yyhGoldDetail.setUserId(goldRebateDto.getTopId());
		yyhGoldDetail.setBusiType(2);
		yyhGoldDetail.setScore(goldRebateDto.getRevenue());
		yyhGoldDetail.setPersent(goldRebateDto.getPersent().longValue());
		goldDetail.add(yyhGoldDetail);
		
		return goldDetail;
	}

	public void doInsert(Map<String, Object> returnMap,Long automaticTrigger, Long crtOpr) {
		RebateDto rebateDto = (RebateDto) returnMap.get("rebateDto");
		List<GoldDetailDto> goldDtailList = (List<GoldDetailDto>) returnMap.get("goldDtailList");
		List<RebateBalanceDto> rebateBalanceList = (List<RebateBalanceDto>) returnMap.get("rebateBalanceList");
		// 代理需要修改的余额
		List<RebateBalanceDto> updateAgentBalances=new ArrayList<RebateBalanceDto>();
		// 运营号需要修改的余额
		List<RebateBalanceDto> updateYYHBalances=new ArrayList<RebateBalanceDto>();
		rebateDto.setAutomaticTrigger(automaticTrigger);
		rebateDto.setCrtDate(new Date().toLocaleString());
		rebateDto.setCrtOpr(crtOpr);
		goldRebateDao.insertRebate(rebateDto);
		
		Long pId = rebateDto.getId();
		for (RebateBalanceDto rebateBalanceDto : rebateBalanceList) {
			rebateBalanceDto.setpId(pId);
			rebateBalanceDto.setCrtDate(new Date().toLocaleString());
			rebateBalanceDto.setCrtOpr(crtOpr);
			//0=普通玩家、1=代理玩家、2=运营号
			if(rebateBalanceDto.getUserType()==1){
				updateAgentBalances.add(rebateBalanceDto);
			}else if(rebateBalanceDto.getUserType()==2){
				updateYYHBalances.add(rebateBalanceDto);
			}
		}
		for (GoldDetailDto goldDetailDto : goldDtailList) {
			goldDetailDto.setpId(pId);
			goldDetailDto.setCrtDate(new Date().toLocaleString());
			goldDetailDto.setCrtOpr(crtOpr);
		}

		goldRebateDao.insertRebateBalances(rebateBalanceList);
		goldRebateDao.insertGoldDetails(goldDtailList);	
		if(updateAgentBalances.size()>0){
			goldRebateDao.updateAgentBalances(updateAgentBalances);
		}
		if(updateYYHBalances.size()>0){
			goldRebateDao.updateYYHBalances(updateYYHBalances);
		}
		System.out.println("");
	}
}
